﻿using PIMS.DBModel;
using PIMS.ORM;
using PIMS.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;

namespace PIMS
{
    public partial class FormSavedDataBag : DockContent
    {
        DataTable initDt = null;
        DataTable dtHis = null;
        int nMax = 0;
        int pageCurrent = 1;
        int nCurrent = 0;
        int pageSize = 0;
        int pageCount = 0;

        public FormSavedDataBag()
        {
            InitializeComponent();
        }

        private void FormSavedData_Load(object sender, EventArgs e)
        {

            if (Common.pimsConfig.GetAppValueByKey("english") == "1")
            {
                label1.Text = "BatchNo";
                label2.Text = "Name";
                label18.Text = "Time range"; //起始时间
                cbTime.Text = "Time range";  //时间范围查询
                cbOrder.Text = "Descending"; //降序查询
                this.buttonQuery.Text = "Query"; //历史工单记录查询
                this.toolStripLabel1.Text = "previous page"; //上一页
                this.toolStripLabel3.Text = "next page"; //下一页
                this.toolStripLabel4.Text = "Total of records = "; //记录总数=
            }
            pageSize = Convert.ToInt32(Common.pimsConfig.GetAppValueByKey("pageSize"));
            // this.dateTimeStart.MinDate = DateTime.Now.AddDays(-365);
            this.dateTimeStart.Value = DateTime.Now.AddDays(-1);
            this.dateTimeEnd.Value = DateTime.Now;

            DgvTools.dataGridView(this.dataGridViewSql);
            DgvTools.AutoGenerateColumns(this.dataGridViewSql, Common.savedDataBagConfigX);
        }

        private void cbTime_CheckedChanged(object sender, EventArgs e)
        {
            if (cbTime.Checked)
            {
                this.dateTimeStart.Enabled = true;
                this.dateTimeEnd.Enabled = true;
            }
            else
            {
                this.dateTimeStart.Enabled = false;
                this.dateTimeEnd.Enabled = false;
            }
        }

        private void buttonQuery_Click(object sender, EventArgs e)
        {
            try
            {
                this.buttonQuery.Enabled = false;
                string brance = " and 1=1";
                string timeStart = dateTimeStart.Value.ToString("yyyy-MM-dd HH:mm:ss");
                string timeEnd = dateTimeEnd.Value.ToString("yyyy-MM-dd HH:mm:ss");
                if (!string.IsNullOrEmpty(this.袋号.Text))
                {
                    brance += " and uid like '%" + this.袋号.Text + "%'";
                }
                if (!String.IsNullOrEmpty(this.箱号.Text))
                {
                    brance += " and boxid like '%" + this.箱号.Text + "'";
                }
                string cmdSql = "";
                if (cbTime.Checked)
                {
                    cmdSql = string.Concat(new string[]
                    {
                      "select * from tb_saveddataBag ",
                      " where productTime between '" + timeStart + "' and '" + timeEnd + "'",
                      " ",
                      brance
                    });
                }
                else
                {
                    cmdSql = string.Concat(new string[]
                   {
                      "select * from tb_saveddataBag ",
                      " where 1=1",
                      " ",
                      brance
                   });
                }
                if (this.cbOrder.Checked)
                {
                    cmdSql += " order by productTime desc";
                }
                BindQueryHistory(this.dataGridViewSql, cmdSql);
                DgvTools.dataGridViewAutoSize(this.dataGridViewSql);
                DgvTools.dataGridViewDisableSort(this.dataGridViewSql);
                MessageBox.Show("查询完毕！", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace, "Err", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // NetLog.CreateLog(ex);
            }
            this.buttonQuery.Enabled = true;
        }

        /// <summary>
        /// orderformhistory
        /// </summary>
        /// <param name="sqlCmd"></param>
        /// <returns></returns>
        public void BindQueryHistory(DataGridView dgv, string sqlCmd)
        {
            this.dtHis = SqlSugarHelper.QueryToDataTable<saveddataBag>(sqlCmd);
            this.recordCount.Text = dtHis.Rows.Count.ToString();
            nMax = dtHis.Rows.Count;  //总记录数

            pageCount = (nMax / pageSize);   //页数＝总记录数/每页显示行数
            if ((nMax % pageSize) > 0) pageCount++;
            pageCurrent = 1;                  //当前页数从1开始
            nCurrent = 0;                     //当前记录数从0开始
            if (nMax == 0)
            {
                lblPageCount.Text = "0";
                txtCurrentPage.Text = "0";
                bdsInfo.DataSource = this.initDt;
                this.dataGridViewSql.DataSource = bdsInfo;
                return;
            }
            else
            {
                LoadData();
            }


        }

        private void LoadData()
        {
            int nStartPos = 0;                   //当前页面开始记录行
            int nEndPos = 0;                     //当前页面结束记录行
            DataTable dtTemp = dtHis.Clone();   //克隆DataTable结构框架
            if (pageCurrent == pageCount)
                nEndPos = nMax;
            else
                nEndPos = pageSize * pageCurrent;
            nStartPos = nCurrent;
            lblPageCount.Text = pageCount.ToString();
            txtCurrentPage.Text = Convert.ToString(pageCurrent);
            try
            {
                //从元数据源复制记录行
                for (int i = nStartPos; i < nEndPos; i++)
                {
                    dtTemp.ImportRow(dtHis.Rows[i]);
                    nCurrent++;
                }
                bdsInfo.DataSource = this.AddSeriNumToDataTable(dtTemp);
                bdnInfo.BindingSource = bdsInfo;
            }
            catch
            {
                bdsInfo.DataSource = this.initDt;
            }

            this.dataGridViewSql.DataSource = bdsInfo;
        }

        /// <summary>
        /// 在DataTable中添加一序号列，编号从1依次递增
        /// </summary>
        /// <param >DataTable</param>
        /// <returns></returns>
        private DataTable AddSeriNumToDataTable(DataTable dt)
        {
            //需要返回的值
            DataTable dtNew;
            if (dt.Columns.IndexOf("序号") >= 0)
            {
                dtNew = dt;
            }
            else //添加一序号列,并且在第一列
            {
                int rowLength = dt.Rows.Count;
                int colLength = dt.Columns.Count;
                DataRow[] newRows = new DataRow[rowLength];

                dtNew = new DataTable();
                //在第一列添加“序号”列
                dtNew.Columns.Add("序号");
                for (int i = 0; i < colLength; i++)
                {
                    dtNew.Columns.Add(dt.Columns[i].ColumnName);
                    //复制dt中的数据
                    for (int j = 0; j < rowLength; j++)
                    {
                        if (newRows[j] == null)
                            newRows[j] = dtNew.NewRow();
                        //将其他数据填充到第二列之后，因为第一列为新增的序号列
                        newRows[j][i + 1] = dt.Rows[j][i];
                    }
                }
                foreach (DataRow row in newRows)
                {
                    dtNew.Rows.Add(row);
                }
            }
            //对序号列填充，从1递增
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dtNew.Rows[i]["序号"] = i + 1;
            }
            return dtNew;
        }

        private void bdnInfo_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (dtHis == null)
            {
                return;
            }

            if (e.ClickedItem.Text == "上一页")
            {
                if ((pageCurrent - 1) <= 0)
                {
                    MessageBox.Show("已经是第一页，请点击“下一页”查看！");
                    return;
                }
                else
                {
                    pageCurrent--;
                    nCurrent = pageSize * (pageCurrent - 1);
                }
                LoadData();
            }
            if (e.ClickedItem.Text == "下一页")
            {
                if ((pageCurrent + 1) > pageCount)
                {
                    MessageBox.Show("已经是最后一页，请点击“上一页”查看！");
                    return;
                }
                else
                {
                    pageCurrent++;
                    nCurrent = pageSize * (pageCurrent - 1);
                }
                LoadData();
            }
        }

        private void FormSavedDataBag_Enter(object sender, EventArgs e)
        {
            this.dateTimeStart.Value = DateTime.Now.AddDays(-1);
            this.dateTimeEnd.Value = DateTime.Now;
        }
    }
}
